package com.gjp.exception;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.authz.UnauthorizedException;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

/**
 * 自定义异常拦截器
 */
@Component
public class MyException extends Exception implements HandlerExceptionResolver
{
	private static final long serialVersionUID = 1L;

	private String message;

	public MyException()
	{
	}

	public MyException(String message)
	{
		super(message);
		this.message = message;
	}

	@Override
	public String getMessage()
	{
		return message;
	}

	public void setMessage(String message)
	{
		this.message = message;
	}

	public ModelAndView resolveException(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception ex)
	{
		// handler为当前处理器适配器执行的对象
		String message = null;

		// 判断异常类型，并做相应错误消息截取。
		if (ex instanceof UnauthorizedException)
		{
			//没有相应权限
			message = ((UnauthorizedException) ex).getMessage();
		}else
		{
			message = "系统出错啦，稍后再试试！错误信息:"+ex.getMessage();
		}

		ModelAndView modelAndView = new ModelAndView();
		// 跳转到相应的处理页面
		modelAndView.addObject("errorMsg", message);
		modelAndView.setViewName("unauthorized");
		return modelAndView;
	}
}
